package com.study.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * Spring中的底层组件的使用
 * @Author ZhuHJay
 * @Date 2021/9/13 23:28
 */
@Component
public class ApplicationComponent implements EnvironmentAware, ApplicationContextAware {

    private static Environment environment;

    private static ApplicationContext applicationContext;

    /** 通过键获取值, 如果获取不到就使用自己传入的空值 **/
    public static String getProperty(String key, String defaultValue){
        return environment.getProperty(key, defaultValue);
    }

    /** 通过键获取值 **/
    public static String getProperty(String key){
        return environment.getProperty(key);
    }

    /** 通过id获取容器中的bean **/
    public static <T> T getBean(String beanName){
        return (T) applicationContext.getBean(beanName);
    }

    /** 通过类型获取容器中的bean **/
    public static <T> T getBean(Class<T> requireType){
        return applicationContext.getBean(requireType);
    }

    @Override
    public void setEnvironment(Environment environment) {
        ApplicationComponent.environment = environment;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationComponent.applicationContext = applicationContext;
    }
}
